package cn.redragon.soa.config.web;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

import cn.redragon.soa.common.web.util.jwt.OAuth2Client;
import feign.RequestInterceptor;
import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

public abstract class BasicAuthFeignConfig extends CommonFeignConfig {

    @Bean
    @ConditionalOnMissingBean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor(getUser(), getPassword());
    }

    @Bean
    @ConditionalOnBean(value = {BasicAuthRequestInterceptor.class, OAuth2Client.class})
    public RequestInterceptor basic2tokenRequestInterceptor(@Autowired final OAuth2Client oAuth2Client) {
        return template -> {
            //convert basic auth to jwt token
            template.removeHeader(AUTHORIZATION);
            template.header(AUTHORIZATION, oAuth2Client.getAuthHeader(this.getUser(), this.getPassword()));
        };
    }

    protected abstract String getUser();

    protected abstract String getPassword();
}
